<?php


namespace app\admin\controller;


use app\admin\common\helper\Response;
use app\admin\library\Auth;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\Department;
use app\BaseController;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Exception;
use think\exception\PDOException;
use think\facade\Db;
use think\facade\Env;
use think\facade\Event;
use think\facade\View;
use think\Request;

class Admin extends BaseController
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];
    protected $group = [];

    public function initialize()
    {
        parent::initialize();

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                $temp[$n['id']] = $n['name'];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result = $temp;
            }
            $groupdata = $result;
        }
        $this->group = $groupdata;
        View::assign('group', $groupList);
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 信息读取
     */
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');

            $where = array();
            if ($request->has('username') && !empty($request->get('username'))) {
                $where[] = array("username", "like", "%" . $request->get('username') . "%");
            }
            if ($request->has('mobile') && !empty($request->get('mobile'))) {
                $where[] = array("mobile", "like", "%" . $request->get('mobile') . "%");
            }
            if ($request->has('email') && !empty($request->get('email'))) {
                $where[] = array("email", "like", "%" . $request->get('email') . "%");
            }
            if ($request->has('role') && !empty($request->get('role'))) {
                $user_id = Db::table("auth_group_access")->field("uid")->where("group_id", $request->get('role'))->select();
                $uid = "";
                foreach ($user_id as $key => $value) {
                    $uid .= $value['uid'] . ',';
                }

                $where[] = array("id", "in", rtrim($uid, ','));
            }

            $result = \app\admin\model\Admin::with(['AuthGroupAccess' => ['AuthGroup'],'AuthGroups','dept'])->where($where)->where('id', 'in', $this->childrenAdminIds)->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
                $pinjie = "";
                foreach ($item['AuthGroupAccess'] as $k => $v) {
                    $pinjie .= $v['AuthGroup']['name'] . ',';
                }
                $item['rules'] = rtrim($pinjie, ',');
                $item['dept_name'] = $item['dept']['name'] ?? '请分配部门';
            })->toArray();

            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }

        return View::fetch();
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * 保存管理员
     */
    public function add(Request $request)
    {
        if ($request->isAjax()) {
            $data = $request->param();
            $data['dept_id'] = $data['department_id'];
            $data['password'] = md5(sha1($request->param('password')));
            try {
                $hasAdmin = \app\admin\model\Admin::where('username', $request->param('username'))->find();
                if (!empty($hasAdmin)) {
                    return json(['code' => 400, 'url' => '', 'msg' => '用户名已经存在！']);
                }
                $hasPhone = \app\admin\model\Admin::where('mobile', $request->param('mobile'))->find();
                if (!empty($hasPhone)) {
                    return json(['code' => 400, 'url' => '', 'msg' => '手机号已经存在！']);
                }
                $hasEmail = \app\admin\model\Admin::where('email', $request->param('email'))->find();
                if (!empty($hasEmail)) {
                    return json(['code' => 400, 'url' => '', 'msg' => '邮箱已经存在！']);
                }
                $admin = \app\admin\model\Admin::create($data, ['username', 'password', 'nickname', 'mobile', 'email', 'status', 'birthday', 'lunar','department_id','dept_id']);
                $group = explode(',', $this->request->param("select"));
                $group = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $admin->id, 'group_id' => $value];
                }
                $AuthGroupAccess = new AuthGroupAccess();
                $AuthGroupAccess->saveAll($dataset);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
        }
        return View::fetch();
    }

    //用户列表
    public function layim_list()
    {
        $mine = [];
        $mine['username'] = $this->auth->nickname;
        $mine['id'] = $this->auth->id;
        $mine['status'] = "online";
        $mine['sign'] = "在深邃的编码世界，做一枚轻盈的纸飞机";
        $mine['avatar'] = $this->auth->portrait;
        $friend_arr = [];
        $group = AuthGroup::field('id,name')->select();
        $i = 0;
        foreach ($group as $k=>$v){
//            if ($v['id'] == $this->auth->id){ //删除当前用户
//                continue;
//            }
            $friend_arr[]['groupname'] = $v['name'];
            $friend_arr[$k]['id'] = $k;
            $adminList = Db::name("auth_group_access")
            ->alias("aga")
            ->join("admins a", "aga.uid=a.id")
            ->field("a.*")
            ->where("aga.group_id", $v['id']) //1为角色组ID
            ->select();
            foreach ($adminList as $key=>$value){
//                if ($value['id'] == $this->auth->id){ //删除当前用户
//
//                    continue;
//                }
                $friend_arr[$k]['list'][$key]['username'] = $value['nickname'];
                $friend_arr[$k]['list'][$key]['id'] = $value['id'];
                $friend_arr[$k]['list'][$key]['status'] = "online";
                $friend_arr[$k]['list'][$key]['sign'] = "在深邃的编码世界，做一枚轻盈的纸飞机";
                if (!empty($value['portrait'])){
                    $portrait = $value['portrait'];
                }else{
                    $portrait = '/static/layuiadmin/style/res/template/character.jpg';
                }
                $friend_arr[$k]['list'][$key]['avatar'] = $portrait;
            }
            $i++;
        }
        $group_arr = [];
        $group_arr['groupname'] = "安玛尔";
        $group_arr['id'] = 1;
        $group_arr['avatar'] = "//tva1.sinaimg.cn/crop.0.0.200.200.50/006q8Q6bjw8f20zsdem2mj305k05kdfw.jpg";

        $data = [
            'code' => 0,
            'msg' => "",
            'data' => [
                'mine' => $mine,
                'friend' =>$friend_arr,
                'group'=>[$group_arr]
            ]
        ];
        return json($data);
    }

    public function getMembers(){
        $group = \app\admin\model\Admin::select();
        $friend_arr = [];
        foreach ($group as $key=>$value){
            $friend_arr[]['username'] = $value['nickname'];
            $friend_arr[$key]['id'] = $value['id'];
            $friend_arr[$key]['status'] = "online";
            $friend_arr[$key]['sign'] = "在深邃的编码世界，做一枚轻盈的纸飞机";
            if (!empty($value['portrait'])){
                $portrait = $value['portrait'];
            }else{
                $portrait = '/static/layuiadmin/style/res/template/character.jpg';
            }
            $friend_arr[$key]['avatar'] = $portrait;

        }
        $data = [
            'code' => 0,
            'msg' => "",
            'data' => [
                'list'=>$friend_arr
            ]
        ];
        return json($data);
    }
    /**
     * @param $id 当前ID
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 编辑页面
     */
    public function edit(Request $request, $id)
    {
        $model = \app\admin\model\Admin::find($id);
        if ($request->isAjax()) {
            Db::startTrans();
            $id = $request->param('id'); //当前ID
            $password = $request->param('password');
            $data = $request->only(['username', 'mobile', 'email', 'nickname', 'status', 'birthday', 'lunar','department_id','dept_id']);
            if (!empty($password)) {
                $data['password'] = md5(sha1($password));
            }
            $admin = \app\admin\model\Admin::find($id);
            $admin->save($data);
            // 先移除所有权限
            AuthGroupAccess::destroy(function ($query) use ($id) {
                $query->where('uid', '=', $id);
            }, true);
            $group = explode(',', $this->request->param("select"));
            // 过滤不允许的组别,避免越权
            $group = array_intersect($this->childrenGroupIds, $group);
            $dataset = [];
            foreach ($group as $value) {
                $dataset[] = ['uid' => $id, 'group_id' => $value];
            }
            $AuthGroupAccess = new AuthGroupAccess();
            $AuthGroupAccess->saveAll($dataset);
            Db::commit();
            return json(['code' => 200, 'url' => '', 'msg' => '编辑成功！']);
        }
        View::assign('id', $id);
        View::assign('model', $model);
        return View::fetch('edit');
    }

    //编辑节点选中
    public function groupTreeEdit(Request $request)
    {
        $id = $request->param('id');
        $grouplist = $this->auth->getGroups($id);

        $list = collection(AuthGroup::select())->toArray();
        $groupList = [];
        foreach ($list as $k => $v) {
            $groupList[$v['id']] = $v;
        }
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $nodeList = [];
        $list = [];
        foreach ($this->group as $k => $v) {
            if (isset($groupList[$k])) {
                $groupList[$k]['name'] = $v;
                $list[] = $groupList[$k];
            }
        }
        foreach ($list as $key => $value) {
            $state = in_array($value['id'], $groupids);
            $nodeList[] = array('name' => $value['name'], 'value' => $value['id'], 'selected' => $state);
        }
        return json($nodeList);
    }

    /**
     * @param $id
     * @return \think\response\Json
     * 删除用户
     */
    public function delete($ids = "")
    {
        try {
            if ($ids) {
                $ids = explode(',', $ids);
                $count = \app\admin\model\Admin::destroy(array_values($ids));
                if ($count) {
                    return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
                }
            }
//            $admin = \app\admin\model\Admin::find($id);
////            Event::trigger('AdminLog','删除');die();
//            $admin->delete();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return json(['code' => 200, 'url' => '', 'msg' => '单点删除成功！']);
    }

    //下拉菜单
    public function groupTree()
    {
        $list = collection(AuthGroup::select())->toArray();

        $groupList = [];
        foreach ($list as $k => $v) {
            $groupList[$v['id']] = $v;
        }

        $list = [];
        foreach ($this->group as $k => $v) {
            if (isset($groupList[$k])) {
                $groupList[$k]['name'] = $v;
                $list[] = $groupList[$k];
            }
        }

        $data = []; //转换到对应的格式
        foreach ($list as $k1 => $v1) {
            $data[]['name'] = $v1['name'];
            $data[$k1]['value'] = $v1['id'];

        }
        return json($data);
    }

    //部门
    public function dept(Request $request){
        $list = collection(Department::select())->toArray();
        $data = []; //转换到对应的格式
        foreach ($list as $k1 => $v1) {
            $data[]['name'] = $v1['name'];
            $data[$k1]['value'] = $v1['id'];
        }
        return json($data);
    }

    //编辑节点选中
    public function departmentEdit(Request $request)
    {
        $id = $request->param('id');
        $grouplist = \app\admin\model\Admin::find($id);

        $list = Department::select()->toArray();
        $groupids = [];
        foreach ($list as $k => $v) {
            $groupids[] = $v['id'];
        };
        $nodeList = [];
        foreach ($list as $key => $value) {
            if ($value['id'] == $grouplist['department_id']){
                $state = true;
            }else{
                $state = false;
            }
            $nodeList[] = array('name' => $value['name'], 'value' => $value['id'], 'selected' => $state);
        }
        return json($nodeList);
    }

    //编辑节点选中
    public function deptEdit(Request $request)
    {
        $id = $request->param('id');
        $grouplist = \app\admin\model\Admin::find($id);

        $list = Department::select()->toArray();
        $groupids = [];
        foreach ($list as $k => $v) {
            $groupids[] = $v['id'];
        };
        $nodeList = [];
        foreach ($list as $key => $value) {
            if ($value['id'] == $grouplist['dept_id']){
                $state = true;
            }else{
                $state = false;
            }
            $nodeList[] = array('name' => $value['name'], 'value' => $value['id'], 'selected' => $state);
        }
        return json($nodeList);
    }

    /**
     * @param Request $request 批量删除存在BUG
     */
    public function batchDelete(Request $request)
    {
//        $ids = $request->post('ids');
//        \app\admin\model\Admin::destroy($ids);
//        return json(['code' => 200, 'url' => '', 'msg' => '多点删除成功！']);

    }

    /**
     * 注销登录存在BUG
     */
    public function logout()
    {
        $this->auth->logout();

        $this->success(('Logout successful'), 'index/login');
    }

    //导入excel
    public function import(Request $request)
    {
        $file = $request->file('file');

        $filePath = \think\facade\Filesystem::disk('public')->putFile('excel', $file, 'uniqid');
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $fieldArr = ['用户名' => 'username', '昵称' => 'nickname', '手机号' => 'mobile', '邮箱' => 'email', '生日' => 'birthday', '阳历/农历' => 'lunar'];
        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load('storage/' . $filePath)) {
                return json(['code' => 400, 'url' => '', 'msg' => 'Unknown data format']);
            }

            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }

                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            return json(['code' => 400, 'url' => '', 'msg' => $exception->getMessage()]);
        }
        if (!$insert) {
            return json(['code' => 400, 'url' => '', 'msg' => 'No rows were updated！']);
        }
        try {
            $admin = new \app\admin\model\Admin();
            $admin->saveAll($insert);
            return json(['code' => 200, 'url' => '', 'msg' => '成功！']);
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            return json(['code' => 400, 'url' => '', 'msg' => $msg]);
        }
    }
}